﻿using BarTender;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing.Printing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Drawing;
using Newtonsoft.Json.Linq;
using System.Windows.Shapes;
using Path = System.IO.Path;

namespace BaseUi.Tool
{
    public class ApplicationTool
    {
        public static void ProRePrint(BarTender.Application btapp, string printModel, BoxInfo boxinfo)
        {
            //todo:标签
            string filePath = AppDomain.CurrentDomain.BaseDirectory + "标签打印.btw";
            BarTender.Format btFormat = btapp.Formats.Open(filePath, false, "");
            btFormat.PrintSetup.IdenticalCopiesOfLabel = 1;  //设置同序列打印的份数 
            btFormat.SetNamedSubStringValue("IMEI", boxinfo.IMEI); //向bartender模板传递变量 
            btFormat.SetNamedSubStringValue("TIME", boxinfo.Time.ToString()); //向bartender模板传递变量 
            btFormat.PrintOut(true, false); //第二个false设置打印时是否跳出打印属性
            btFormat.Close(BarTender.BtSaveOptions.btSaveChanges); //退出时是否保存标签

            Logs.Write("打印"+boxinfo.IMEI+boxinfo.Time.ToString(), LogsType.InfoPrinted, DateTime.Now);
        }

        internal static void ProcsRePrint(Application btapp, string printModel)
        {
            var dt = DateTime.Now;
            string filePath = AppDomain.CurrentDomain.BaseDirectory + "标签打印.btw";
            BarTender.Format btFormat = btapp.Formats.Open(filePath, false, "");
            btFormat.PrintSetup.IdenticalCopiesOfLabel = 1;  //设置同序列打印的份数 
            btFormat.SetNamedSubStringValue("IMEI", "159824522485524"); //向bartender模板传递变量 
            btFormat.SetNamedSubStringValue("TIME", dt.ToString()); //向bartender模板传递变量 
            btFormat.PrintOut(true, false); //第二个false设置打印时是否跳出打印属性
            btFormat.Close(BarTender.BtSaveOptions.btSaveChanges); //退出时是否保存标签

            Logs.Write("测试打印", LogsType.InfoPrinted, DateTime.Now);
        }
        //internal static void PsocsRePrint(Application btapp, string printModel)
        //{
        //    Type type = Type.GetTypeFromProgID("DLabel.Application");
        //    if (type == null)
        //    {
        //        throw new Exception("未找到DLabel COM组件，请确认已安装DLabel");
        //    }

        //    // 创建DLabel应用程序对象
        //    //dynamic dlabel = Activator.CreateInstance(Type.GetTypeFromProgID("DLabel.Application"));

        //    //// 打开标签模板
        //    //dynamic document = dlabel.Documents.Open(AppDomain.CurrentDomain.BaseDirectory + "星恒IOT IMIE.ddl");

        //    //// 设置变量值
        //    ////document.Variables["csname"].Value = "智能手机X10";
        //    ////document.Variables["ProductCode"].Value = "SPX2023001";
        //    ////document.Variables["Price"].Value = "¥2999";
        //    ////document.Variables["BatchNo"].Value = "B20230501";

        //    //// 打印设置
        //    //document.Printer.Settings.Copies = 1;

        //    //// 执行打印
        //    //document.PrintOut();

        //    //// 释放资源
        //    //System.Runtime.InteropServices.Marshal.ReleaseComObject(document);
        //    //System.Runtime.InteropServices.Marshal.ReleaseComObject(dlabel);
        //    //Logs.Write("测试打印", LogsType.InfoPrinted, DateTime.Now);
        //}
        internal static string PrintWithCsvDDL(string templatePath, Dictionary<string, string> variables, string patth)
        {
            // 生成临时 CSV 文件
            string csvPath = Path.GetTempFileName();
            try
            {
                // CSV 格式：变量名,变量值
                using (StreamWriter sw = new StreamWriter(csvPath))
                {
                    sw.WriteLine("VariableName,VariableValue"); // 表头
                    foreach (var kv in variables)
                    {
                        sw.WriteLine($"\"{kv.Key}\",\"{EscapeCsvValue(kv.Value)}\"");
                    }
                }

                // 打印命令
                ProcessStartInfo psi = new ProcessStartInfo
                {
                    FileName = GetDLabelExePath(patth),
                    Arguments = $"/F=\"{templatePath}\" /D=\"{csvPath}\" /P",
                    //Verb = "runas", // 请求管理员权限
                    UseShellExecute = false,
                    CreateNoWindow = true,
                    //RedirectStandardError = true
                };
                using (Process process = Process.Start(psi))
                {
                    process.WaitForExit(5000);
                    if (process.ExitCode != 0)
                        throw new Exception($"打印失败 (代码:{process.ExitCode})");
                }
                return "OK";
            }
            catch (Exception ee)
            {

                return ee.ToString() ;
            }
            finally
            {
                File.Delete(csvPath); // 清理临时文件
            }
        }

        internal static string EscapeCsvValue(string value)
            => value.Replace("\"", "\"\""); // CSV 转义

        internal static string GetDLabelExePath(string patth)
        {
            string[] paths = {
            @"C:\Program Files\DLabel\DLabel.exe",
            @"C:\Program Files (x86)\DLabel\DLabel.exe",
            @"D:\DLabel\DLabel.exe"
        };
            paths[2]=patth;
            return paths.FirstOrDefault(File.Exists)
                   ?? throw new FileNotFoundException("找不到 DLabel.exe");
        }
    }
}


